import time

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect

from utils.tencent.cos import create_bucket
from web import models
from web.forms.project import ProjectModelForm


def project_list(request):
    """项目列表"""
    if request.method == 'GET':

        # 这里是查询出所有我创建的、我参与的project，然后循环两个列表，分别添加到对应的字典项目中
        my_project_list = models.Project.objects.filter(creator=request.lxyker.user)
        join_project_list = models.ProjectUser.objects.filter(user=request.lxyker.user)
        project_dict = {'star': [], 'mine': [], 'join': []}
        for row in my_project_list:
            if row.is_star:
                project_dict['star'].append({'value': row, 'type': 'mine'})
            else:
                project_dict['mine'].append(row)
        for row in join_project_list:
            if row.is_star:
                project_dict['star'].append({'value': row.project, 'type': 'join'})
            else:
                project_dict['join'].append(row.project)

        form = ProjectModelForm(request)
        return render(request, 'web/project_list.html', {'form': form, 'project_dict': project_dict})
    elif request.method == 'POST':
        form = ProjectModelForm(request, data=request.POST)
        if form.is_valid():
            # 为项目创建一个桶

            bucket = '{}-{}-1258158324'.format(request.lxyker.user.mobile_phone, int(time.time()))
            region = 'ap-beijing'
            create_bucket(bucket=bucket, region=region)

            # 验证通过，应该创建项目。此时用户只提交了 项目名、颜色、文本描述 。应该+创建者
            form.instance.bucket = bucket            # 把桶、区域写入数据库
            form.instance.region = region
            form.instance.creator = request.lxyker.user  # 这个是创建者
            # 创建项目
            instance = form.save()

            # 给新创建的项目初始化问题的类型，便于创建问题时有默认的问题类型可选择
            issues_type_object_list = list()
            for item in models.IssuesType.PROJECT_INIT_LIST:
                issues_type_object_list.append(models.IssuesType(project=instance, title=item))
            models.IssuesType.objects.bulk_create(issues_type_object_list)

            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    if project_type == 'mine':
        models.Project.objects.filter(id=project_id, creator=request.lxyker.user).update(is_star=True)
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.lxyker.user).update(is_star=True)
        return redirect('project_list')
    return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
    if project_type == 'mine':
        models.Project.objects.filter(id=project_id, creator=request.lxyker.user).update(is_star=False)
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.lxyker.user).update(is_star=False)
        return redirect('project_list')
    return HttpResponse('请求错误')